<template>
  <div class="create-order">
    <div class="order-container">
      <!-- 收货地址 -->
      <div class="address-section">
        <div class="section-header">
          <h3>收货地址</h3>
          <el-button type="primary" plain size="small" :icon="Plus" @click="showAddressDialog">添加新地址</el-button>
        </div>
        <div class="address-list" v-if="addressList.length > 0">
          <el-table :data="addressList" stripe style="width: 100%" border>
            <el-table-column prop="" label="选择" width="80" align="center">
              <template #default="scope">
                <el-radio v-model="selectedAddressId" :label="scope.row.id" class="hide-label">
                  <span class="radio-content">&nbsp;</span>
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="" label="默认地址" width="100">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <el-tag effect="light" type="danger" round v-if="scope.row.isDefault === '1'" disabled>
                    默认地址
                  </el-tag>
                  <el-tag effect="plain" type="primary" round v-else style="cursor: pointer;"
                    @click="setDefaultAddress(scope.row)">
                    设为默认
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="收货人" width="120" />
            <el-table-column prop="phone" label="电话" width="180" />
            <el-table-column prop="address" label="详细地址" min-width="300" />
          </el-table>
        </div>
        <div v-else class="no-address">
          <el-empty description="暂无收货地址">
            <el-button type="primary" @click="showAddressDialog">添加收货地址</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product-section">
        <div class="section-header">
          <h3>商品信息</h3>
        </div>
        <div class="product-info">
          <img :src="product.image" class="product-image" />
          <div class="product-details">
            <div class="title">{{ product.title }}</div>
            <div class="price-info">
              <div class="price">￥{{ product.price }}</div>
              <div class="delivery-type">
                <el-tag :type="product.postType === 0 ? 'warning' : 'success'" effect="light">
                  {{ product.postType === 0 ? '快递配送' : '自提' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-section">
        <div class="section-header">
          <h3>支付方式</h3>
        </div>
        <div class="payment-methods">
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wxpay">
              <div class="payment-method-item">
                <img src="@/assets/img/wxpay.png" alt="微信支付" class="payment-icon" />
                <span>微信支付</span>
              </div>
            </el-radio>
            <el-radio label="alipay">
              <div class="payment-method-item">
                <img src="@/assets/img/alipay.png" alt="支付宝支付" class="payment-icon" />
                <span>支付宝支付</span>
              </div>
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 订单金额 -->
      <div class="order-total">
        <div class="total-item">
          <span>商品金额：</span>
          <span class="price">￥{{ product.price }}</span>
        </div>
        <div class="total-item">
          <span>运费：</span>
          <span class="price">￥{{ product.postType === 0 ? '10' : '0' }}</span>
        </div>
        <div class="total-item total">
          <span>实付金额：</span>
          <span class="price">￥{{ totalAmount }}</span>
        </div>
      </div>

      <!-- 提交订单按钮 -->
      <div class="submit-order">
        <!-- <el-button @click="goBack">返回</el-button> -->
        <el-button type="primary" :loading="submitting" @click="submitOrder">提交订单</el-button>
      </div>
    </div>

    <!-- 地址管理对话框 -->
    <el-dialog v-model="addressDialogVisible" :title="dialogTitle" width="500px" center>
      <el-form ref="addressFormRef" :model="addressForm" :rules="rules" label-width="80px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input type="textarea" v-model="addressForm.address" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddress">取消</el-button>
          <el-button type="primary" @click="confirmAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useProductDetailStore } from '@/stores'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { createOrder } from '@/api/payment'
import useAddress from '@/hooks/useAddress'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const route = useRoute()
const productStore = useProductDetailStore()
const userStore = useUserStore()

// 商品信息
const product = computed(() => {
  if (!productStore.productDetail.id && route.query.productId) {
    // 如果store中没有商品信息，但有productId，则重新获取
    productStore.getProductDetail(route.query.productId as string)
  }
  return productStore.productDetail
})

// 地址相关
const { addressList, addressForm, rules, getAddressList, saveAddress, resetForm, setDefaultAddress } = useAddress()
const selectedAddressId = ref('')
const addressDialogVisible = ref(false)
const dialogTitle = ref('新增收货地址')
const addressFormRef = ref<FormInstance>()

// 支付方式
const paymentMethod = ref('wxpay')

// 计算总金额
const totalAmount = computed(() => {
  return product.value.price + (product.value.postType === 0 ? 10 : 0)
})

// 提交状态
const submitting = ref(false)

// 显示地址对话框
const showAddressDialog = () => {
  dialogTitle.value = '新增收货地址'
  addressDialogVisible.value = true
}

// 取消地址
const cancelAddress = () => {
  addressDialogVisible.value = false
  resetForm(addressFormRef.value)
}

// 确认地址
const confirmAddress = async () => {
  if (!addressFormRef.value) return
  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      await saveAddress(addressFormRef.value)
      addressDialogVisible.value = false
      await getAddressList()
    }
  })
}

// 页面加载时
onMounted(async () => {
  // 检查是否有商品ID
  if (!route.query.productId) {
    ElMessage.warning('商品信息不存在')
    router.back()
    return
  }

  // 获取商品信息
  if (!productStore.productDetail.id) {
    await productStore.getProductDetail(route.query.productId as string)
  }

  // 获取地址列表
  await getAddressList()
  // 自动选中默认地址，如果没有默认地址则选中第一个
  const defaultAddress = addressList.value.find(addr => addr.isDefault === '1')
  if (defaultAddress) {
    selectedAddressId.value = defaultAddress.id || ''
  } else if (addressList.value.length > 0) {
    selectedAddressId.value = addressList.value[0].id || ''
  }
})

// 监听地址列表变化，确保新增地址后也能自动选中
watch(addressList, (newList) => {
  if (!selectedAddressId.value && newList.length > 0) {
    const defaultAddress = newList.find(addr => addr.isDefault === '1')
    if (defaultAddress) {
      selectedAddressId.value = defaultAddress.id || ''
    } else {
      selectedAddressId.value = newList[0].id || ''
    }
  }
}, { deep: true })

// 提交订单
const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  // try {
    submitting.value = true

    // 获取选中的地址信息
    const selectedAddress = addressList.value.find(addr => addr.id === selectedAddressId.value)
    if (!selectedAddress) {
      ElMessage.warning('收货地址信息有误')
      return
    }

    // 检查商品信息是否完整
    if (!product.value.id || !product.value.price) {
      ElMessage.warning('商品信息不完整')
      return
    }

    // 创建订单数据
    const orderData = {
      productId: product.value.id,
      userId: userStore.user.id,
      productUserId: product.value.userId,
      productTitle: product.value.title,
      productImg: Array.isArray(product.value.image) ? product.value.image[0] : product.value.image,
      productPrice: Number(product.value.originalPrice || product.value.price),
      productSellPrice: Number(product.value.price),
      productType: product.value.typeId,
      productNum: 1,
      productPost: product.value.postType === 0 ? 10 : 0,
      productPostStatus: product.value.postType,
      productMoney: Number(product.value.price),
      productInfo: product.value.intro,
      buyMoneyAll: Number(totalAmount.value),
      buyMoney: Number(totalAmount.value),
      postMode: product.value.postType === 0 ? '物流发货' : '用户自提',
      postUsername: selectedAddress.name,
      postPhone: selectedAddress.phone,
      postAddress: selectedAddress.address,
      dealStatus: 2,
      payStatus: 0
    }

    // 调用创建订单API
    // const res = await createOrder(orderData)

  //   if (res.code === 0) {
  //     ElMessage.success('订单创建成功')
  //     // 跳转到支付页面，带上订单ID
  //     router.push({
  //       path: '/payment/pay',
  //       query: {
  //         orderId: res.data.id,
  //         paymentMethod: paymentMethod.value
  //       }
  //     })
  //   } else {
  //     ElMessage.error(res.msg || '订单创建失败')
  //   }
  // } catch (error: any) {
  //   console.error('创建订单失败:', error)
  //   ElMessage.error(error.response?.data?.msg || error.message || '订单创建失败，请稍后重试')
  // } finally {
  //   submitting.value = false
  // }
}

// // 返回上一页
// const goBack = () => {
//   router.back()
// }
</script>

<style lang="less" scoped>
.create-order {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;

  .order-container {
    max-width: 800px;
    margin: 0 auto;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }
    }

    .address-section {
      margin-bottom: 30px;
      background: #fafafa;
      padding: 20px;
      border-radius: 4px;

      .address-list {
        :deep(.el-table) {
          border-radius: 8px;
          overflow: hidden;

          .el-table__header-wrapper {
            th {
              background-color: #f5f7fa;
              color: #606266;
              font-weight: bold;
            }
          }

          .el-radio {
            margin-right: 0;

            .el-radio__label {
              display: none;
            }
          }

          .el-tag {
            margin: 0 auto;
          }
        }
      }

      .no-address {
        text-align: center;
        padding: 40px 20px;
        background: #fff;
        border-radius: 8px;
      }
    }

    .product-section {
      margin-bottom: 30px;
      background: #fafafa;
      padding: 20px;
      border-radius: 4px;

      .product-info {
        display: flex;
        background: #fff;
        padding: 15px;
        border-radius: 4px;

        .product-image {
          width: 120px;
          height: 120px;
          object-fit: cover;
          border-radius: 4px;
          margin-right: 20px;
        }

        .product-details {
          flex: 1;

          .title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
          }

          .price-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .price {
              color: #ff4d4f;
              font-size: 20px;
              font-weight: bold;
            }
          }
        }
      }
    }

    .payment-section {
      margin-bottom: 30px;
      background: #fafafa;
      padding: 20px;
      border-radius: 4px;

      .payment-methods {
        .el-radio-group {
          display: flex;
          gap: 20px;
        }

        .payment-method-item {
          display: flex;
          align-items: center;
          padding: 10px;

          .payment-icon {
            width: 24px;
            height: 24px;
            margin-right: 8px;
          }
        }
      }
    }

    .order-total {
      margin: 30px 0;
      padding: 20px;
      background: #fafafa;
      border-radius: 4px;

      .total-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        font-size: 14px;

        &.total {
          margin-top: 15px;
          padding-top: 15px;
          border-top: 1px solid #eee;
          font-size: 18px;
          font-weight: bold;

          .price {
            color: #ff4d4f;
            font-size: 24px;
          }
        }

        .price {
          color: #ff4d4f;
        }
      }
    }

    .submit-order {
      text-align: center;

      .el-button {
        width: 120px;
        height: 45px;
        font-size: 16px;
        margin: 0 10px;
      }
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  border-radius: 8px;

  .el-dialog__header {
    margin: 0;
    padding: 20px 20px 10px;
    text-align: center;
  }

  .el-dialog__body {
    padding: 30px 20px;
  }

  .el-dialog__footer {
    padding: 10px 20px 20px;
    text-align: center;
  }
}
</style>
